package mytomcat.util;

import mytomcat.mapper.TBlogMapper;
import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author swc
 * @date 2020/6/2 0002 下午 15:09
 */
public class MyBatisUtil {

    public final static String MYBATIS_XML_FILE ="mybatis-application.xml";

//    public static Configuration  initConfig(){
//        Properties properties = new Properties();
//        properties.setProperty("driver", "com.mysql.jdbc.Driver");
//        properties.setProperty("url", "jdbc:mysql://127.0.0.1:3306/mybatis");
//        properties.setProperty("username", "root");
//        properties.setProperty("password", "123456");
//        PooledDataSourceFactory pooledDataSourceFactory = new PooledDataSourceFactory();
//        pooledDataSourceFactory.setProperties(properties);
//        DataSource dataSource = pooledDataSourceFactory.getDataSource();
//
//        TransactionFactory transactionFactory = new JdbcTransactionFactory();
//        Environment environment = new Environment("development", transactionFactory, dataSource);
//
//        Configuration configuration = new Configuration(environment);
//        configuration.addMapper(TBlogMapper.class);
//        return configuration;
//    }

    /**
     * 功能描述: 通过xml文件得到
     * @param resource
     * @return: org.apache.ibatis.session.SqlSessionFactory
     * @author: swc
     * @date: 2020/6/2 0002 下午 15:15
    */
    public static SqlSessionFactory  getSqlSessionFactory(String resource)throws Exception{
        resource =resource==null ||"".equals(resource.trim()) ? MyBatisUtil.MYBATIS_XML_FILE:resource;
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory;
    }

//    /**
//     * 功能描述: 通过java配置得到
//     * @param
//     * @return: org.apache.ibatis.session.SqlSessionFactory
//     * @author: swc
//     * @date: 2020/6/2 0002 下午 15:15
//    */
//    public static SqlSessionFactory  getSqlSessionFactoryByConfig()throws Exception{
//        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(initConfig());
//        return sqlSessionFactory;
//    }

}
